package com.whcoding.jpa.service.impl;

import com.whcoding.jpa.dao.DeptDao;
import com.whcoding.jpa.pojo.OrmDeptPO;
import com.whcoding.jpa.service.DeptService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

/**
 * @author Manager
 */
@Service
public class DeptServiceImpl implements DeptService {

	private static final Logger log = LoggerFactory.getLogger(DeptServiceImpl.class);

	@Autowired
	DeptDao deptDao;

	/***
	 *
	 * 1.新增
	 * @param deptVO
	 * @return
	 */
	@Override
	public boolean addDept(OrmDeptPO deptVO) {
		OrmDeptPO saveMode = deptDao.save(deptVO);
		return saveMode.getId() > 0;
	}

	/**
	 * 根据ID 查询数据
	 *
	 * @param id
	 * @return
	 */
	@Override
	public OrmDeptPO queryDeptById(Integer id) {
		Optional<OrmDeptPO> optional = deptDao.findById(id);
		if (optional.isPresent()) {
			return optional.get();
		}
		return new OrmDeptPO();
	}

	/**
	 * 根据DeptName 查询数据
	 *
	 * @param deptName
	 * @return
	 */
	@Override
	public OrmDeptPO queryDeptByDeptName(String deptName) {
		return deptDao.findByDeptName(deptName);
	}

	/**
	 * 查询全部数据
	 *
	 * @return
	 */
	@Override
	public List<OrmDeptPO> queryAllDept() {
		OrmDeptPO deptPO=new OrmDeptPO();
		//根据条件查询数据
		deptPO.setDeptId(1001);
		deptPO.setDeptNo("CG_001");
		List<OrmDeptPO> poList= deptDao.findAll(Example.of(deptPO));

		System.out.println(poList);
		return deptDao.findAll();
	}

	/**
	 * 用户自定义sql 查询
	 *
	 * @return
	 */
	@Override
	public List<OrmDeptPO> queryDeptBySql() {
		//根据ID 获取dept
		OrmDeptPO deptVO = queryDeptById(1);
		if (StringUtils.isEmpty(deptVO.getDeptName())) {
			return null;
		}
		List<OrmDeptPO> deptReslutList = deptDao.queryDeptByName(deptVO.getDeptName());
		log.info("根据deptName获取到的数据为：" + deptReslutList.size());
		return deptReslutList;
	}

	@Override
	public void deleteByDeptId(Long deptId) {
		deptDao.deleteOrmDeptVOByDeptId(deptId);
	}
}
